<template>
    <div ref="containerRef" class="courseContentExerciseView">
        <template v-if="homeworkId">
            <Exercise></Exercise>
        </template>
        <template v-else-if="permission > 1">
            <div class="composingATestPaper">
                <SideNav class="sideNav" :width="350" :menuList="navigationMenuList">
                    <template #title>
                    </template>
                    <template #questionBank>
                        <div class="title">
                            <span class="iconfont icon-likesprogramadvisor-zhinengguwen"></span>
                            <div class="titleText">AI智能组卷</div>
                        </div>
                        <form class="questionBankForm">
                            <div class="inputBox">
                                <span>题目数量：</span>
                                <input type="number" v-model="testPaperParameters.totalQuestionCount" placeholder="请输入题目数量" />
                            </div>
                            <div class="inputBox">
                                <span>题目总分：</span>
                                <input type="number" v-model="testPaperParameters.totalScore" placeholder="请输入总分" />
                            </div>
                            <div class="inputBox">
                                <span>题目难度：</span>
                                <div class="selectBox">
                                    <!-- 下拉框列表 -->
                                    <select class="select" v-model="testPaperParameters.difficulty" aria-label="NewExercisesType">
                                        <option v-for="option in difficultyList" :value="option.difficultyName">{{ option.difficultyName }}</option>
                                    </select>
                                    <span class="iconfont icon-likesprograma-shangyiye1"></span>
                                </div>
                            </div>
                            <div class="inputBox noPadding">
                                <span>知识点：</span>
                            </div>
                            <div class="inputBox">
                                <div class="typeBox listBox maxType">
                                    <div v-if="knowledgeList.length <= 0">无关联知识点</div>
                                    <div class="typeItem" :class="{ 'select': isSelectKnowledge(knowledge) }"
                                        @click="selectKnowledge(knowledge)"
                                        v-for="knowledge in knowledgeList" :key="knowledge.recordId">
                                        {{ knowledge.knowledgeContent }}
                                    </div>
                                </div>
                            </div>
                            <div class="inputBox">
                                <span>其他需求：</span>
                            </div>
                            <div class="inputBox noPadding">
                                <textarea type="text" v-model="testPaperParameters.requirement"
                                    placeholder="请输入组卷需求" />
                            </div>
                            <div class="inputBox">
                                <div class="button butNormal">开&nbsp;&nbsp;始&nbsp;&nbsp;组&nbsp;&nbsp;卷</div>
                            </div>
                        </form>
                    </template>
                    <template #homeworkList>
                        <div class="homeworkList">
                            <div class="homeworkListTitle">
                                作业列表
                            </div>
                            <HomeworkList v-model="homeworkList" @itemClick="selectHomeworkItem" />
                        </div>
                    </template>
                </SideNav>
                <template v-if="selectHomework && editHomework == null">
                    <div class="homeworkContent">
                        <div class="hwHeader">
                            <div class="hwTitle">
                                <div class="hwName">{{selectHomework?.homeworkInfo?.homeworkName}}</div>
                                <div class="hwUpDate">{{selectHomework?.homeworkInfo?.updateDate}}</div>
                            </div>
                            <div class="inputBox">
                                <div class="button butDelete">
                                    <span class="iconfont icon-likesprogramhuishouzhan"></span>
                                    删除
                                </div>
                                <div class="button butNormal" @click="editHomeworkFunc">
                                    <span class="iconfont icon-likesprogrambianji"></span>
                                    编辑
                                </div>
                                <div class="button butNormal"
                                @click="() => {
                                    let homework = selectHomework?.homeworkInfo;
                                    if (homework == null) homework = createTempHomework(selectExercisesList);
                                    showPreviewPaperDialog(createTempHomework(selectExercisesList));
                                }">
                                    <span class="iconfont icon-likesprogrammimakejian"></span>
                                    预览
                                </div>
                                <div class="button butNormal" @click="showPublishPaperDialog(null)">发布</div>
                            </div>
                        </div>
                        <div class="hwPublishListContent">
                            <div class="hwPublishList">
                                <div class="hwPublishItem" v-for="(publishHomework, index) in publishHomeworkList" :key="index">
                                    <div class="hwPublishItemTitle">
                                        <span class="hwPublishItemTitleIconfont iconfont icon-likesprograma-shangyiye1"></span>
                                        <div class="hwPublishItemTitleText">
                                            <div class="hwPublishItemName">
                                                <span class="targetName">{{ publishHomework.cusStudyGroup?.groupName }}</span>
                                                <span class="publishTime">{{ publishHomework.startTime }} - {{ publishHomework.endTime }}</span>
                                            </div>
                                            <!-- 数据 -->
                                            <div class="hwPublishItemTitleTextStatistics">
                                                <div class="hwPublishItemTitleTextPendingReviewCount">
                                                    {{ publishHomework.pendingReviewCount }} 待批阅
                                                </div>
                                                <div class="hwPublishItemTitleTextSubmitCount">
                                                    <span>{{ publishHomework.submitCount }} 已提交</span>
                                                    <span>{{ publishHomework.unSubmitCount }} 未提交</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="inputBox">
                                            <div class="button butDelete">
                                                <span class="iconfont icon-likesprogramhuishouzhan"></span>
                                                删除
                                            </div>
                                            <div class="button butNormal" @click="showPublishPaperDialog(publishHomework)">修改参数</div>
                                        </div>
                                    </div>
                                    <div class="hwPublishItemContent">
                                        <div class="homeworkMember" v-for="(homeworkMember, index) in publishHomework.homeworkMembers" :key="index">
                                            <div class="homeworkMemberUserInfo">
                                                <div class="homeworkMemberUserAvatar">
                                                    <img :src="homeworkMember.courseMember?.userInfo?.avatarPath ? (baseUrl + homeworkMember.courseMember?.userInfo?.avatarPath ) : defaultAvatar()" alt="用户头像">
                                                </div>
                                                <div class="homeworkMemberUserName">{{ homeworkMember.courseMember.userNickName }}</div>
                                            </div>
                                            <!-- 提交信息 -->
                                            <div class="homeworkMemberSubmit" v-if="homeworkMember.ureceiveHwrec">
                                                <div class="homeworkMemberSubmitTime">提交时间：{{ homeworkMember.courseMember.registTime }}</div>
                                                <div class="homeworkMemberScore" v-if="homeworkMember.ureceiveHwrec?.score">得分：<span :class="{
                                                    'warning': homeworkMember.ureceiveHwrec?.score < 60, 'tips': (homeworkMember.ureceiveHwrec?.score >= 60 && homeworkMember.ureceiveHwrec?.score < 85),
                                                    'complete': homeworkMember.ureceiveHwrec?.score >= 85 }">{{ 100 }}</span> 分</div>
                                                <div class="homeworkMemberMarkMan" :class="
                                                    homeworkMember.ureceiveHwrec?.markMan ? 'complete' : 'tips'
                                                ">{{
                                                    homeworkMember.ureceiveHwrec?.markMan ? '已批阅' :
                                                    homeworkMember.ureceiveHwrec?.markTime ? 'AI代批阅' : '待批阅'
                                                }}</div>
                                            </div>
                                            <div class="homeworkMemberSubmit" v-if-else>
                                                <div class="homeworkMemberMarkMan warning">未提交</div>
                                            </div>
                                            <div class="inputBox">
                                                <div class="button" :class="homeworkMember.ureceiveHwrec ? 'butNormal' : 'butDisable'" @click="showPreviewPaperDialog(publishHomework.homeworkInfo)">批阅</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div class="questionBankList">
                        <h3 class="table-title">题目列表</h3>
                        <el-table :data="exercisesList" class="custom-table" 
                            v-if="exercisesList?.length"
                            :cell-style="{ padding: '12px 0' }" 
                            row-key="exercisesId"
                        >
                            <el-table-column prop="exercisesId" label="题号" width="100" align="center" header-align="center" />
                            <el-table-column prop="title" label="题目" min-width="180" />
                            <el-table-column 
                                prop="difficulty" 
                                label="难度" 
                                width="120"
                                align="center"
                                header-align="center"
                            >
                                <template #default="{row}">
                                    <span>{{ row.difficultyText }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200" align="center" header-align="center">
                                <template #default="{ row }">
                                    <div class="inputBox noPadding">
                                        <div class="button" :class="exercisesList?.length > 0 ? 'butNormal' : 'butDisable'"
                                            @click="showShowExercisesDialog(row.exercisesId)">
                                            <span class="iconfont icon-likesprogrammimakejian"></span>
                                            查看
                                        </div>
                                        <div class="button" v-if="isSelectExercises(row)" :class="exercisesList?.length > 0 ? 'butDelete' : 'butDisable'"
                                            @click="selectExercises(row)">
                                            移除
                                        </div>
                                        <div class="button" v-else :class="exercisesList?.length > 0 ? 'butNormal' : 'butDisable'"
                                            @click="selectExercises(row)">
                                            选择
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-empty v-else description="暂无数据" class="empty-tip" />
                        <Pagination ref="questionBanMosel" v-model:currentPage="currentPage" v-model:pageSize="pageSize" v-model:total="total"
                        @updateData="(_courrentPage, _pageSize) => { searchQuestions(_courrentPage, _pageSize); }"/>
                    </div>
                    <div class="selectedList">
                        <h3 class="table-title">题目列表</h3>
                        <h4 class="table-title">
                            已选 {{ selectExercisesList?.length ? selectExercisesList?.length : 0 }} 道题，
                            总分：{{ selectExercisesList.reduce((sum, item) => sum + item.exerciseScore, 0) }}
                        </h4>
                        <div class="table-box" v-if="selectExercisesList?.length">
                            <el-table :data="selectExercisesList"
                            style="width: 100%; height: 100%; overflow-y: 'auto';" >
                                <!-- 表格内容 -->
                                <el-table-column label="分数" width="105" >
                                    <template #default="{ row }">
                                        <div class="inputBox">
                                            <input type="number" v-model="row.exerciseScore" placeholder="请输入分数">
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="题目">
                                    <template #default="{ row }">
                                            <div class="content">{{ row.exercisesId }}：{{ row.exerciseInfo?.title }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="85">
                                    <template #default="{ row }">
                                        <el-button type="danger" size="mini" @click="selectExercises(row.exerciseInfo)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <el-empty v-else description="未选择题目" class="empty-tip" />
                        <div class="inputBox">
                            <div class="button" :class="selectExercisesList?.length > 0 ? 'butNormal' : 'butDisable'"
                            @click="() => {
                                let homework = selectHomework?.homeworkInfo;
                                if (homework == null) homework = createTempHomework(selectExercisesList);
                                showPreviewPaperDialog(createTempHomework(selectExercisesList));
                            }">预览试卷</div>
                            <div class="button" :class="selectExercisesList?.length > 0 ? 'butNormal' : 'butDisable'" @click="showSavePaperDialog">保存试卷</div>
                        </div>
                    </div>
                </template>
            </div>
        </template>
        
        <!-- 题目详细对话框 -->
        <MessageDialog ref="showExercisesDialog">
            <template v-slot:title>
                <span>题目详细</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <CourseContentExerciseContent class="exerciseContent" :exercisesId="showExercisesDialogData" :previewMode="true" :writeMode="false" />
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closeShowExercisesDialog">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="closeShowExercisesDialog">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
        <!-- 保存试卷对话框 -->
        <MessageDialog ref="savePaperDialog">
            <template v-slot:title>
                <span>保存试卷</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <div class="inputBox">
                        <span>试卷名称</span>
                        <input type="text" v-model="editHomework.homeworkName" placeholder="请输入试卷名称" />
                    </div>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closeSavePaperDialog">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="savePaper">
                    <span>保存</span>
                </div>
            </template>
        </MessageDialog>
        <!-- 发布试卷对话框 -->
        <MessageDialog ref="publishPaperDialog">
            <template v-slot:title>
                <span>发布作业</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent publishPaperContent">
                    <div class="inputBox">
                        <span>发布类型</span>
                        <div class="selectBox">
                            <select class="select" v-model="publichPaperData.publishType" placeholder="请选择发布类型">
                                <option label="作业" value="Test"></option>
                                <option label="考试" value="Exam"></option>
                            </select>
                            <span class="iconfont icon-likesprograma-shangyiye1"></span>
                        </div>
                        <span>过期是否可以提交</span>
                        <div class="selectBox">
                            <select class="select" v-model="publichPaperData.canSubmitOverTime" placeholder="请选择过期是否可以提交">
                                <option label="否" :value="false"></option>
                                <option label="是" :value="true"></option>
                            </select>
                            <span class="iconfont icon-likesprograma-shangyiye1"></span>
                        </div>
                    </div>
                    <div class="inputBox">
                        <span>发布目标</span>
                        <div class="selectBox">
                            <select class="select" v-model="publichPaperData.targetId" placeholder="请选择发布目标">
                                <option v-for="option in targetList" :label="option.groupName" :value="option.groupId"></option>
                            </select>
                            <span class="iconfont icon-likesprograma-shangyiye1"></span>
                        </div>
                    </div>
                    <div class="inputBox">
                        <span>结束时间</span>
                        <input type="datetime-local" v-model="publichPaperData.endTime" placeholder="请选择结束时间" />
                    </div>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closePublishPaperDialog">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="publishPaper">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
        <!-- 预览试卷对话框 -->
        <MessageDialog ref="previewPaperDialog">
            <template v-slot:title>
                <span>预览试卷</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <CourseContentExercise :homework="previewPaper" />
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closePreviewPaperDialog">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="closePreviewPaperDialog">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
        <!-- 消息对话框 -->
        <MessageDialog ref="messageDialog">
            <template v-slot:title>
                <span>{{ messageDialogData.title }}</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <div class="messageBox" :class="messageDialogData.type">
                        <div class="message" v-for="message in messageDialogData.message">{{ message }}</div>
                    </div>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closeMessage">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="closeMessage">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
    </div>
</template>

<script lang="ts">
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElTable, ElTableColumn } from 'element-plus';
import Exercise from "@/views/course/courseDetails/courseContent/courseContentResourcesView/CourseContentExerciseView.vue"
import SideNav, { SideNavMenu } from '@/components/SideNav.vue';
import { courseApi, exercisesApi, homeworkApi } from "@/api/course/Course";
import { CourseDifficulty, CusStudyGroup, Exercises, Homework, HomeworkExercises, KnowledgePoint, PublishHomework } from "@/types/Course";
import MessageDialog from '@/components/MessageDialog.vue';
import CourseContentExerciseContent from '@/components/course/CourseContentExerciseContent.vue';
import CourseContentExercise from "@views/course/courseDetails/courseContent/courseContentResourcesView/CourseContentExerciseView.vue";
import { userAvatar as defaultAvatar } from '@/types/Base64Image';
import { baseUrl } from '@/util/request';

export default {
    name: 'courseContentExerciseView'
}
</script>

<script setup lang="ts">
    const route = useRoute();
    const courseId = ref(0);
    // 权限
    const permission = ref<number>(0);
    
    // 分页参数
    const currentPage = ref(1);
    const pageSize = ref(11);
    const total = ref(0);

    // 作业列表
    const homeworkList = ref<Homework[]>();
    const selectHomework = ref<PublishHomework>(null);
    const publishHomeworkList = ref<PublishHomework[]>();
    // 获取作业列表
    const getHomeworkList = async () => {
        homeworkList.value = await homeworkApi.getHomeworkList(courseId.value, 'course').catch(() => {
            return [];
        });
    }

    // 获取指定作业的作业发布信息
    const getPublishHomeworkByHomeworkId = async (homeworkId: number) => {
        publishHomeworkList.value = await homeworkApi.publish.getPublishHomeworkByHomeworkId(homeworkId).catch(() => {
            return null;
        });
    }

    // 选择作业
    const selectHomeworkItem = (item: PublishHomework) => {
        if (selectHomework.value != null && selectHomework.value.publishId === item.publishId) {
            selectHomework.value = null;
            editHomework.value = null;
            selectExercisesList.value = [];
            return;
        }
        selectHomework.value = item;
        editHomework.value = null;
        getPublishHomeworkByHomeworkId(item.homeworkId);
    }

    // 题目列表
    const exercisesList = ref<Exercises[]>();
    // 选择的题目
    const selectExercisesList = ref<HomeworkExercises[]>([]);
    // 获取题目列表
    const editHomework = ref<Homework>(null);

    // 编辑试卷
    const editHomeworkFunc = () => {
        editHomework.value = JSON.parse(JSON.stringify(selectHomework.value.homeworkInfo));
        selectExercisesList.value = JSON.parse(JSON.stringify(selectHomework.value.homeworkInfo.exercises));
        if (selectExercisesList.value == null) selectExercisesList.value = [];
    }
    // 保存试卷
    const savePaper = () => {
        if (selectExercisesList.value == null || editHomework.value == null)
        {
            ElMessage.error('保存失败');
            return;
        }
        homeworkApi.setHomework(editHomework.value, selectExercisesList.value).then(() => {
            ElMessage.success('保存成功');
            getHomeworkList();
            closeSavePaperDialog();
        }).catch(() => {
            ElMessage.error('保存失败');
        });
    }

    // 保存试卷对话框
    const savePaperDialog = ref();
    const showSavePaperDialog = () => {
        if (editHomework.value == null) editHomework.value = {
	        targetId: courseId.value,
	        homeworkName: "",
	        homeworkType: "course",
	        fullMark: selectExercisesList.value.reduce((sum, item) => sum + item.exerciseScore, 0),
	        exerciseCount: selectExercisesList.value.length,
	        exercises: selectExercisesList.value
        }
        savePaperDialog.value.ShowModal();
    }
    const closeSavePaperDialog = () => {
        editHomework.value = null;
        selectExercisesList.value = [];
        savePaperDialog.value.Close();
    }

    // 发布作业对话框
    const publishPaperDialog = ref();
    const publichPaperData = ref<PublishHomework>();
    // 目标列表
    const targetList = ref<CusStudyGroup[]>([]);
    const showPublishPaperDialog = async (publichPaper: PublishHomework) => {
        targetList.value = await courseApi.courseClass.getClassList(courseId.value).catch(() => {
            return [];
        });
        if (publichPaper == null) publichPaperData.value = {
            publishId: 0,
            targetId: 0,
            homeworkId: selectHomework.value.homeworkId,
            publishType: "Test",
            startTime: getNowFormatted(),
            endTime: getNowFormatted(),
            canSubmitOverTime: false,
            exerciseShuffle: false,
            optionShuffle: false,
            publishDate: "",
            status: 0,
            score: 0,
            homeworkMembers: [],
            cusStudyGroup:null,
        }; else publichPaperData.value = JSON.parse(JSON.stringify(publichPaper));
        publishPaperDialog.value.ShowModal();
    }
    function getNowFormatted() {
        const pad = n => n.toString().padStart(2, '0');
        const now = new Date();
        return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
    }
    const closePublishPaperDialog = () => {
        publishPaperDialog.value.Close();
    }
    // 发布作业
    const publishPaper = () => {
        if (publichPaperData.value == null)
        {
            ElMessage.error('参数错误！');
            return;
        }
        if (publichPaperData.value.targetId == 0)
        {
            ElMessage.error('请选择发布目标！');
            return;
        }
        homeworkApi.publish.publishHomework(publichPaperData.value).then(() => {
            ElMessage.success('发布成功');
            getHomeworkList();
            getPublishHomeworkByHomeworkId(publichPaperData.value.homeworkId);
            closePublishPaperDialog();
        }).catch(() => {
            ElMessage.error('发布失败');
        });
    }

    // 知识点列表
    const knowledgeList = ref<KnowledgePoint[]>([]);
    // 难度列表
    const difficultyList = ref<CourseDifficulty[]>([
        {
            difficultyId: 0,
            difficultyName: "简单"
        },
        {
            difficultyId: 1,
            difficultyName: "一般"
        },
        {
            difficultyId: 2,
            difficultyName: "困难"
        }
    ]);
    // 试卷参数
    const testPaperParameters = ref<{
        // 题目数量
        totalQuestionCount: number,
        // 总分
        totalScore: number,
        // 难度
        difficulty: string,
        // 知识点
        knowledgeList: KnowledgePoint[],
        // 其他需求
        requirement: string
    }>({
        totalQuestionCount: 10,
        totalScore: 100,
        knowledgeList: [],
        difficulty: difficultyList.value[0].difficultyName,
        requirement: ''
    });

    // 预览试卷对话框
    const previewPaperDialog = ref();
    const previewPaper = ref<Homework[]>(null);
    const createTempHomework = (HomeworkExercises: HomeworkExercises[]): Homework => {
        return {
            targetId: courseId.value,
            homeworkName: "作业预览",
            homeworkType: "course",
            fullMark: HomeworkExercises.reduce((sum, item) => sum + item.exerciseScore, 0),
            exerciseCount: HomeworkExercises.length,
            exercises: JSON.parse(JSON.stringify(HomeworkExercises))
        }
    }
    const showPreviewPaperDialog = (homework: Homework) => {
        previewPaper.value = JSON.parse(JSON.stringify(homework));
        previewPaperDialog.value.ShowModal();
    }
    const closePreviewPaperDialog = () => {
        previewPaper.value = null;
        previewPaperDialog.value.Close();
    }

    // 消息对话框
    const messageDialog = ref(null);
    const messageDialogData = ref({
        title: '',
        message: [''],
        type: 'success',
    });
    // const showMessage = (title: string, message: string[], type: string) => {
    //     messageDialogData.value = { title, message, type };
    //     messageDialog.value.ShowModal();
    // }
    const closeMessage = () => {
        messageDialog.value.Close();
    }
    
    // 查看习题对话框
    const showExercisesDialog = ref();
    const showExercisesDialogData = ref<number>(0);
    // 显示查看习题对话框
    const showShowExercisesDialog = async (exercisesId: number) => {
        showExercisesDialogData.value = exercisesId;
        showExercisesDialog.value.ShowModal();
    }
    // 关闭查看习题对话框
    const closeShowExercisesDialog = () => {
        showExercisesDialog.value.Close();
        showExercisesDialogData.value = 0;
    }
    
    // 获取知识点列表
    const getKnowledgeList = async () => {
        knowledgeList.value = (await courseApi.chapter.knowledge.getKnowledgePoint(courseId.value, null)).data;
        testPaperParameters.value.knowledgeList = knowledgeList.value.slice();
    }
    
    // 判断知识点是否已选择
    const isSelectKnowledge = (knowledge: KnowledgePoint) => {
        if (testPaperParameters.value.knowledgeList.find(_knowledge => _knowledge.recordId === knowledge.recordId)) {
            return true;
        }
        return false;
    }
    // 选择知识点
    const selectKnowledge = (knowledge: KnowledgePoint) => {
        if (isSelectKnowledge(knowledge)) {
            // 移除
            testPaperParameters.value.knowledgeList = testPaperParameters.value.knowledgeList.filter(_knowledge => _knowledge.recordId !== knowledge.recordId);
            return;
        }
        testPaperParameters.value.knowledgeList.push(knowledge);
    }

    const navigationMenuList = ref<SideNavMenu[]>([
        { iconName: 'icon-likesprogrampinggu', titleText: '试卷', slotName: 'homeworkList'},
        { iconName: 'icon-likesprogramadvisor-zhinengguwen', titleText: 'AI组卷', slotName: 'questionBank', onClick: () => {
            selectHomework.value = null;
        }}
    ]);
    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    const homeworkId = ref(null);

    const searchQuestions = async (_courrentPage: number, _pageSize: number) => {
        try {
            const res = await exercisesApi.getExercises(
                courseId.value, 
                null, 
                _courrentPage, 
                _pageSize
            );
            exercisesList.value = res.list;
            pageSize.value = res.pageSize;
            total.value = res.total;
        } catch (error) {
            console.error(error);
        }
    };

    const isSelectExercises = (exercises: Exercises) => {
        if (selectExercisesList.value.find(_exercises => _exercises.exercisesId === exercises.exercisesId)) {
            return true;
        }
        return false;
    }
    // 选择题目
    const selectExercises = (exercises: Exercises) => {
        console.log(exercises);
        if (isSelectExercises(exercises)) {
            // 移除
            selectExercisesList.value = selectExercisesList.value.filter(_exercises => _exercises?.exercisesId !== exercises.exercisesId);
            return;
        }
        selectExercisesList.value.push({
            exercisesId: exercises.exercisesId,
            exerciseScore: 1,
            exerciseInfo: exercises
        });
    }

    // route.query.chapterId
    // 监听路由参数的变化
    watch(
        () => ({
            courseIdParam: route.params.courseId,
            homeworkIdParam: route.query.homeworkId
        }), async ({courseIdParam, homeworkIdParam}) => {
        homeworkId.value = parseSafeInt(homeworkIdParam);
        courseId.value = parseSafeInt(courseIdParam);
        // 获取权限
        permission.value = (await courseApi.getMemberPermission(courseId.value));
        // 获取难度列表
        // courseTypeApi.getDifficulty().then(res => {
        //     difficultyList.value = res;
        // });
        // 获取作业列表
        getHomeworkList();
        // 获取知识点列表
        getKnowledgeList();
    },
    { immediate: true });
</script>


<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
.courseContentExerciseView {
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.composingATestPaper {
    width: 100%;
    height: 100%;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 0.2);
    box-shadow: 0px 0px 10px rgba(0, 0, 0, .1);
}

.sideNav {
    flex-shrink: 0;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, .1);
}


/* 聊天列表标题内容 */
.sideNav .title {
    width: calc(100% - 20px);
    height: 60px;
    margin: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(65, 185, 255, 0.1), rgba(65, 185, 255, 0.05));
    color: #41B9FF;
    text-shadow: 0 0 10px rgba(65, 185, 255, .3);
    border-radius: 10px;
    overflow: hidden;
    white-space: nowrap;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
}

.sideNav .title .iconfont {
    font-size: 42px;
    margin-right: 10px;
    animation: float 3s ease-in-out infinite;
}

.sideNav .title .titleText {
    font-size: 20px;
    letter-spacing: 5px;
    font-weight: bold;
    font-family: "artisticFonts";
    opacity: 0.9;
}

@keyframes float {

    0%,
    100% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-5px);
    }
}

/* 添加响应式设计 */
@media screen and (max-width: 768px) {
    .sideNav .title .titleText {
        font-size: 16px;
        letter-spacing: 3px;
    }

    .sideNav .title .iconfont {
        font-size: 36px;
    }
}

.questionBankForm {
    width: 100%;
    padding: 20px;
    padding-top: 0px;
    overflow: hidden;
}

.homeworkList {
    width: 100%;
    height: 100%;
}

/* 作业列表标题 */
.homeworkListTitle {
    display: flex;
    align-items: center;
    height: 60px;
    padding: 0px 10px;
    background-color: rgba(255, 255, 255, 1);
}

/* 作业内容 */
.homeworkContent {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

.homeworkContent .hwHeader {
    flex-shrink: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 60px;
    padding: 0 20px;
    background-color: rgba(255, 255, 255, 1);
}

.homeworkContent .hwHeader .hwTitle {
    flex-shrink: 0;
    width: calc(100% - 320px);
    display: flex;
    /* 多行 */
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
}
.homeworkContent .hwHeader .hwTitle .hwName {
    font-size: 16px;
}
.homeworkContent .hwHeader .hwTitle .hwUpDate {
    font-size: 14px;
    color: rgba(100, 100, 100, 1);
}

/* 作业发布记录 */
.homeworkContent .hwPublishListContent { 
    width: 100%;
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
    padding: 20px;
}
.homeworkContent .hwPublishList {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 20px;
}
.homeworkContent .hwPublishList .hwPublishItem {
    width: 100%;
    border-radius: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.5);
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle { 
    width: 100%;
    height: 55px;
    padding-right: 10px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background-color: rgba(255, 255, 255, 1);
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleIconfont { 
    flex-shrink: 0;
    font-size: 20px;
    height: 100%;
    width: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleText {
    flex: 1;
    display: flex;
    flex-direction: space-between;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleText .hwPublishItemName { 
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleText .hwPublishItemTitleTextStatistics { 
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0px 20px;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleTextStatistics .hwPublishItemTitleTextPendingReviewCount,
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleText .hwPublishItemName .targetName { 
    font-size: 16px;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleTextStatistics .hwPublishItemTitleTextSubmitCount,
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .hwPublishItemTitleText .hwPublishItemName .publishTime { 
    font-size: 14px;
    color: rgba(100, 100, 100, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .targetName { 
    flex-shrink: 0;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .publishTime { 
    flex-shrink: 0;
}
.homeworkContent .hwPublishList .hwPublishItem .hwPublishItemTitle .inputBox {
    flex-shrink: 0;
    width: 180px;
}
/* 发布内容 */
.homeworkContent .hwPublishItemContent {
    width: 100%;
    /* height: 400px; */
    padding: 2px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 2px;
    overflow: hidden;
}
.homeworkContent .hwPublishItemContent .homeworkMember {
    width: 100%;
    height: 45px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 1);
    border-radius: 5px;
    padding: 0px 10px;
}
.homeworkContent .hwPublishItemContent .homeworkMember .homeworkMemberUserInfo {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
}
.homeworkContent .hwPublishItemContent .homeworkMember .homeworkMemberSubmit {
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    padding: 0px 10px;
}
.homeworkContent .hwPublishItemContent .homeworkMember .inputBox {
    width: 80px;
    flex-shrink: 0;
}
.homeworkContent .hwPublishItemContent .homeworkMember .homeworkMemberUserInfo .homeworkMemberUserAvatar {
    width: 35px;
    height: 35px;
    border-radius: 50%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 2px solid rgba(65, 185, 255, 1);
}
.homeworkContent .hwPublishItemContent .homeworkMember .homeworkMemberUserInfo .homeworkMemberUserAvatar img {
    width: 100%;
    height: 100%;
}

.homeworkContent .hwPublishItemContent .homeworkMember .complete{
    color: rgba(65, 185, 255, 1);
}
.homeworkContent .hwPublishItemContent .homeworkMember .tips {
    color: rgba(255, 153, 0, 1);
}
.homeworkContent .hwPublishItemContent .homeworkMember .warning {
    color: rgba(255, 0, 0, 1);
}


.questionBankList {
    flex: 1;
    min-width: 0;
    height: 100%;
    padding: 20px;
    background-color: rgba(255, 255, 255, .5);
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
}

.selectedList {
    flex-shrink: 0;
    width: 400px;
    height: 100%;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, .1);
    background-color: rgba(255, 255, 255, .5);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding-bottom: 10px;
}

.selectedList .table-title {
    flex-shrink: 0;
    width: 100%;
    padding: 20px;
}

.selectedList .table-box {
    flex: 1;
    width: 100%;
    min-width: 0;
    overflow-y: auto;
}

.custom-table {
    width: 100%;
    border-radius: 10px;
    overflow: hidden;
    margin: 15px 0px;
}

.selectedList .inputBox {
    flex-shrink: 0;
    width: 100%;
    padding: 10px;
}

.publishPaperContent {
    width: 400px;
}

.dialogContent {
    padding: 0px 10px;
}

/* 编辑课程对话框 */
.dialogContent form {
    width: 600px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}

.dialogContent .exerciseContent {
    width: 100%;
    height: 100%;
    min-width: 1000px;
    max-height: 800px;
    overflow: hidden;
    overflow-y: auto;
}

.inputBox {
    width: 100%;
    padding: 10px 0px;
    font-size: 14px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
}
.inputBox.noPadding {
    padding: 0px 0px;
    align-items: flex-start;
}

/* 输入框 */
.inputBox span {
    /* 单行 */
    flex-shrink: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.inputBox .selectBox, .inputBox input, .inputBox textarea {
    width: 100%;
    height: 35px;
    font-size: 16px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
    background-color: rgba(255, 255, 255, 1);
}
.inputBox.noPadding textarea {
    height: 200px;
    resize: none; /* 禁止调整大小 */
    padding: 3px 10px;
    line-height: 28px;
}
.inputBox input:focus, .inputBox textarea:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

.inputBox input, .inputBox .typeBox {
    width: 100%;
    font-size: 14px;
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
    overflow-y: auto;
    display: grid;
    background-color: rgba(255, 255, 255, 1);
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
}
.inputBox input {
    height: 35px;
    border: 2px solid rgba(200, 200, 200, 1);
}
.inputBox .typeBox {
    min-height: 40px;
    max-height: 80px;
    resize: none; /* 禁止调整大小 */
    padding: 3px 10px;
    line-height: 28px;
}
.inputBox .typeBox.maxType {
    padding: 10px;
    max-height: 250px;
}
.inputBox .typeBox.slectList {
    padding: 10px;
    max-height: 250px;
}
.inputBox input:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}
.inputBox .listBox {
    border: 2px solid rgba(200, 200, 200, 1);
}

/* 列表 */
.inputBox .typeBox .typeItem {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100px;
    height: 30px;
    font-size: 14px;
    border-radius: 10px;
    border: 2px solid rgba(200, 200, 200, 1);
}
.inputBox .typeBox.slectList .typeItem {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}
.inputBox .typeBox .typeItem:hover {
    color: rgba(65, 185, 255, 1);
    border: 2px solid rgba(65, 185, 255, 1);
}
.inputBox .typeBox .typeItem.select {
    color: rgb(255, 255, 255);
    border: 2px solid rgba(65, 185, 255, 1);
    background: rgba(65, 185, 255, 1);
}

/* 表单按钮 */
.inputBox .button {
    width: 100%;
    height: 35px;
    overflow: hidden;
    padding: 0px 5px;
    border-radius: 5px;
    transition: .3s all;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 5px;
}
.inputBox .button .iconfont {
    font-size: 18px;
    min-width: 0px;
    width: 18px;
    overflow: hidden;
}
/* 正常按钮 */
.inputBox .button.butNormal {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, 1);
}
.inputBox .button.butNormal:hover {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, .8);
}
.inputBox .button.butNormal:active {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(65, 185, 255, .9);
    transition: all .1s;
}
/* 删除按钮 */
.inputBox .button.butDelete {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, 1);
}
.inputBox .button.butDelete:hover {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, .7);
}
.inputBox .button.butDelete:active {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(255, 0, 0, .9);
    transition: all .1s;
}
/* 失效按钮 */
.inputBox .button.butDisable {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(185, 185, 185, 1);
}

/* 禁用按钮 */
.inputBox .button.disable {
    color: aliceblue;
    background-color: rgba(180, 180, 180, 1);
}
.inputBox .button.disable:hover {
    background-color: rgba(180, 180, 180, 0.8);
}
.inputBox .button.disable:active {
    transition: .1s all;
    background-color: rgba(180, 180, 180, 1);
}

/* 上传资源列表 */
.inputBox .draggableDataList {
    width: 100%;
    max-height: 300px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 5px;
    overflow-y: auto;
}
.inputBox .draggableDataList .draggableData {
    width: 100%;
    height: 35px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}
.inputBox .draggableDataList .draggableData .progress {
    height: 50%;
    top: 50%;
    transform: translateY(-50%) translateX(10px);
    position: absolute;
    border-radius: 5px;
    z-index: 1;
    background-color: rgba(65, 185, 255, .5);
}
.inputBox .draggableDataList .draggableData .draggableDataInfo {
    width: 100%;
    height: 100%;
    border-radius: 5px;
    padding-right: 5px;
    z-index: 2;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: rgba(255, 255, 255, .5);
    backdrop-filter: blur(.5rem);
    -webkit-backdrop-filter: blur(.5rem);
    -moz-backdrop-filter: blur(.5rem);
    -ms-backdrop-filter: blur(.5rem);
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoMove {
    flex-shrink: 0;
    width: 35px;
    height: 35px;
    min-width: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoNum {
    flex-shrink: 0;
    padding: 0px 10px;
    min-width: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoIcon {
    flex-shrink: 0;
    min-width: 0px;
    display: flex;
    justify-content: center;
    
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoIcon img {
    width: 25px;
    height: 25px;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoName {
    flex: 1;
    padding: 0px 10px;
    min-width: 0px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoType {
    flex-shrink: 0;
    max-width: 150px;
    padding: 0px 5px;
    min-width: 0px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoSize {
    flex-shrink: 0;
    max-width: 100px;
    min-width: 0px;
    padding: 0px 5px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoName span,
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoType span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .button {
    font-size: 14px;
    min-width: 0px;
    height: 25px;
    padding: 0px 5px;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .button .iconfont {
    font-size: 16px;
    margin-right: 2px;
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoType.fail {
    color: rgba(255, 0, 0, 1);
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoType.warning {
    color: rgb(255, 145, 0);
}
.inputBox .draggableDataList .draggableData .draggableDataInfo .infoType.success {
    color: rgba(65, 185, 255, 1)
}

/* 下拉框 */
.inputBox .selectBox {
    width: 100%;
    border-radius: 5px;
    font-size: 16px;
    padding: 0px 0px;
    color: #333;
    outline: none;
    position: relative;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    transition: .3s all;
}
.inputBox .selectBox:focus-within {
    border: 2px solid rgba(65, 185, 255, 1);
}
.inputBox .selectBox:focus-within .iconfont {
    color: rgba(65, 185, 255, 1);
}
.inputBox .selectBox .select {
    width: 100%;
    padding: 0px 10px;
    padding-right: 35px;
    border: 0px solid #ccc;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0);
    font-size: 14px;
    position: relative;
    z-index: 1;
    color: #333;
    outline: none;
    cursor: pointer;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}
.inputBox .selectBox .iconfont {
    width: 30px;
    min-width: 0px;
    font-size: 20px;
    position: absolute;
    right: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(-90deg);
    transition: .3s all;
    color: rgba(100, 100, 100, 1);
}

/* 对话框底部按钮 */
.dialogFooterButton {
    width: 100%;
    height: 65px;
    position: relative;
    display: flex;
    color: rgba(65, 185, 255, 1);
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: .3s all;
}
.dialogFooterButton:hover {
    background-color: rgba(200, 200, 200, .15);
}
.dialogFooterButton:active {
    transition: .1s all;
    background-color: rgba(220, 220, 220, .1);
}
.dialogFooterButton .line {
    width: 100%;
    border-right: 1px solid rgba(200, 200, 200, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}

</style>
